package com.can.Service;


import com.can.Mapper.GoodBadMapper;
import com.can.domain.po.Goodbad;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class SyncService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    GoodBadMapper goodBadMapper;
    @Autowired
    GoodBadService goodBadService;

    /**
     * 每分钟同步一次 Redis 中的点赞和踩数据到数据库
     */
    @Scheduled(fixedRate = 10000) // 十秒
    public void syncRedisToDatabase() {
        // 获取所有以 "post:" 开头的 Redis 键
        Set<String> keys = redisTemplate.keys("post:*");
        if (keys == null || keys.isEmpty()) {
            return; // 如果没有匹配的键，直接返回
        }
        HashMap<Integer, Goodbad> map = new HashMap<>();
        for (String key : keys) {

            String[] slist=key.split(":");
            int curid=Integer.parseInt(slist[1]);
//            没有对象就创建，有就取出
            Goodbad cur=map.getOrDefault(curid, new Goodbad(curid,0,0));

            if (slist[2].equals("good")){
                cur.setGood(Integer.parseInt(redisTemplate.opsForValue().get(key)));
            }else{
                cur.setBad(Integer.parseInt(redisTemplate.opsForValue().get(key)));
            }
            map.put(curid,cur);
        }

        goodBadService.saveOrUpdateBatch(map.values());
        System.out.println("✅ 点赞数据成功同步至数据库");

    }
}